import { HealthData, HealthDataTrend, BloodPressureReading, ExerciseData } from '../models/HealthData';
import { Storage } from '@kit.StorageKit';

// 健康数据服务类
export class HealthDataService {
  private static instance: HealthDataService;
  private storageKeyPrefix = 'health_data_';

  // 单例模式
  public static getInstance(): HealthDataService {
    if (!HealthDataService.instance) {
      HealthDataService.instance = new HealthDataService();
    }
    return HealthDataService.instance;
  }

  // 添加健康数据
  async addHealthData(data: HealthData): Promise<boolean> {
    try {
      // 获取现有数据
      const existingData = await this.getHealthDataByType(data.patientId, data.type);
      existingData.push(data);
      
      // 保存到存储
      await Storage.setOrCreate(this.storageKeyPrefix + data.patientId + '_' + data.type, JSON.stringify(existingData));
      
      return true;
    } catch (error) {
      console.error('添加健康数据失败:', error);
      return false;
    }
  }

  // 获取特定类型的健康数据
  async getHealthDataByType(patientId: string, type: string): Promise<HealthData[]> {
    try {
      const data = await Storage.get(this.storageKeyPrefix + patientId + '_' + type);
      return data ? JSON.parse(data) : [];
    } catch (error) {
      console.error('获取健康数据失败:', error);
      return [];
    }
  }

  // 获取所有健康数据
  async getAllHealthData(patientId: string): Promise<HealthData[]> {
    try {
      const types = ['bloodSugar', 'bloodPressure', 'heartRate', 'weight', 'exercise'];
      let allData: HealthData[] = [];
      
      for (const type of types) {
        const data = await this.getHealthDataByType(patientId, type);
        allData = [...allData, ...data];
      }
      
      // 按时间排序
      return allData.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
    } catch (error) {
      console.error('获取所有健康数据失败:', error);
      return [];
    }
  }

  // 获取健康数据趋势
  async getHealthDataTrend(patientId: string, type: string, trendType: 'daily' | 'weekly' | 'monthly', days: number = 30): Promise<HealthDataTrend> {
    try {
      const endDate = new Date();
      const startDate = new Date();
      startDate.setDate(startDate.getDate() - days);
      
      const data = await this.getHealthDataByType(patientId, type);
      const filteredData = data.filter(item => {
        const itemDate = new Date(item.timestamp);
        return itemDate >= startDate && itemDate <= endDate;
      });
      
      // 根据趋势类型处理数据
      const dataPoints = this.processDataForTrend(filteredData, trendType);
      
      return {
        type: trendType,
        startDate,
        endDate,
        dataPoints
      };
    } catch (error) {
      console.error('获取健康数据趋势失败:', error);
      return {
        type: trendType,
        startDate: new Date(),
        endDate: new Date(),
        dataPoints: []
      };
    }
  }

  // 处理趋势数据
  private processDataForTrend(data: HealthData[], trendType: 'daily' | 'weekly' | 'monthly') {
    // 这里实现数据聚合逻辑，根据趋势类型进行日/周/月的聚合
    // 简化版本，实际应用中需要更复杂的聚合算法
    return data.map(item => ({
      timestamp: new Date(item.timestamp),
      value: this.extractValue(item)
    }));
  }

  // 提取数值（处理不同类型的数据）
  private extractValue(data: HealthData): number {
    if (data.type === 'bloodPressure' && typeof data.value !== 'number') {
      const bp = data.value as BloodPressureReading;
      return (bp.systolic + bp.diastolic) / 2; // 返回平均压作为示例
    } else if (data.type === 'exercise' && typeof data.value !== 'number') {
      const exercise = data.value as ExerciseData;
      return exercise.duration; // 返回运动时长
    } else {
      return data.value as number;
    }
  }

  // 删除健康数据
  async deleteHealthData(patientId: string, dataId: string): Promise<boolean> {
    try {
      const types = ['bloodSugar', 'bloodPressure', 'heartRate', 'weight', 'exercise'];
      
      for (const type of types) {
        const data = await this.getHealthDataByType(patientId, type);
        const filteredData = data.filter(item => item.id !== dataId);
        
        if (filteredData.length !== data.length) {
          await Storage.setOrCreate(this.storageKeyPrefix + patientId + '_' + type, JSON.stringify(filteredData));
          return true;
        }
      }
      
      return false;
    } catch (error) {
      console.error('删除健康数据失败:', error);
      return false;
    }
  }

  // 导入健康数据（从设备或文件）
  async importHealthData(patientId: string, importedData: HealthData[]): Promise<number> {
    try {
      let importedCount = 0;
      
      for (const data of importedData) {
        const success = await this.addHealthData({
          ...data,
          patientId,
          id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
          source: 'import'
        });
        
        if (success) importedCount++;
      }
      
      return importedCount;
    } catch (error) {
      console.error('导入健康数据失败:', error);
      return 0;
    }
  }

  // 数据同步（模拟与外部设备或服务同步）
  async syncHealthData(patientId: string): Promise<boolean> {
    try {
      // 这里实现与外部设备或服务的同步逻辑
      // 简化版本，实际应用中需要与具体的设备SDK或API集成
      console.log('同步健康数据中...');
      
      // 模拟同步延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      return true;
    } catch (error) {
      console.error('同步健康数据失败:', error);
      return false;
    }
  }
}